<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-card class="box-card">
          <!-- 组织架构 -->
          <div class="head-container">
            <el-input v-model="deptName" placeholder="请输入部门" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree
              ref="treeBox"
              :filter-node-method="filterNode"
              :data="deptTree"
              :props="deptTreeProps"
              :expand-on-click-node="false"
              default-expand-all
              :highlight-current="true"
              node-key="departmentId"
              @node-click="handleNodeClick"
            />
          </div>
        </el-card>
      </el-col>

      <!--卡片-->
      <el-col :span="20">
        <el-card class="box-card">
          <!-- 搜索 -->
          <el-form v-show="showSearch" :model="queryForm" :inline="true" label-width="68px">
            <el-form-item prop="userName">
              <el-input v-model="queryForm.userName" placeholder="请输入用户名" clearable size="small" prefix-icon="el-icon-search" />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="createDate"
                :default-time="['00:00:00','23:59:59']"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button plain type="primary" icon="el-icon-search" size="mini" @click="searchQuery">搜索</el-button>
              <el-button plain type="warning" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 新增，编辑，删除，导出 -->
          <el-button
            v-hasPermi="['admin','system:user:add']"
            type="primary"
            small
            icon="el-icon-plus"
            size="mini"
            @click="addDialogVisible = true"
          >新增
          </el-button>
          <el-button
            v-hasPermi="['admin','system:user:edit']"
            :disabled="ids.length===1?false:true"
            type="success"
            small
            icon="el-icon-edit"
            style="margin:10px"
            size="mini"
            @click="editBtn(ids[0])"
          >修改
          </el-button>
          <el-button
            v-hasPermi="['admin','system:user:del']"
            :disabled="ids.length>0?false:true"
            type="danger"
            small
            icon="el-icon-delete"
            style="margin:10px"
            size="mini"
            @click="delAllBtn(ids)"
          >删除
          </el-button>
          <el-button
            v-hasPermi="['admin','system:user:export']"
            type="warning"
            small
            icon="el-icon-download"
            style="margin:10px"
            size="mini"
            @click="exportClick"
          >导出
          </el-button>
          <!-- 搜索，刷新，表头工具栏 -->
          <right-bar :show-search.sync="showSearch" :table-data="tableColumns" @queryTable="refresh()" />

          <!--用户表格-->
          <el-table :data="listForm" stripe style="font-size: 12px;width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column v-if="hasTable('userId',tableColumns)" prop="userId" label="ID" width="55" />
            <el-table-column v-if="hasTable('userName',tableColumns)" prop="userName" label="用户名" />
            <el-table-column v-if="hasTable('nickName',tableColumns)" prop="nickName" label="昵称" />
            <el-table-column v-if="hasTable('deptName',tableColumns)" prop="deptName" label="部门" />
            <el-table-column v-if="hasTable('sex',tableColumns)" prop="sex" label="性别">
              <template slot-scope="scope">
                {{ scope.row.sex | sexFormat }}
              </template>
            </el-table-column>
            <el-table-column v-if="hasTable('status',tableColumns)" label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="0"
                  @change="userStateChanged(scope.row)"
                /></template>
            </el-table-column>
            <el-table-column v-if="hasTable('remark',tableColumns)" prop="remark" label="备注" />
            <el-table-column v-if="hasTable('createTime',tableColumns)" prop="createTime" label="创建日期" width="180" />
            <!--操作-->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button v-hasPermi="['admin','system:user:edit']" type="text" size="mini" @click="editBtn(scope.row.userId)">编辑</el-button>
                <el-button v-show="scope.row.userId!==1" v-hasPermi="['admin','system:user:del']" type="text" size="mini" @click="delBtn(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!--分页区域-->
          <el-pagination
            background
            :current-page="pageNumber"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />

        </el-card>
      </el-col>
    </el-row>

    <!--添加用户对话框-->
    <el-dialog title="新增用户" :close-on-click-modal="false" :visible.sync="addDialogVisible" width="600px" @close="addHandleClose">
      <span>
        <el-form ref="addFormRef" :inline="true" :model="addForm" :rules="addFormRules" label-width="70px">
          <el-form-item label="账号" prop="userName">
            <el-input v-model="addForm.userName" />
          </el-form-item>
          <el-form-item label="密码" prop="passWord">
            <el-input v-model="addForm.passWord" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="addForm.nickName" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email" />
          </el-form-item>
          <el-form-item label="部门" prop="deptId">
            <treeselect v-model="addForm.deptId" :options="deptTree" :normalizer="normalizer" style="width: 185px;" placeholder="请选择部门" />
          </el-form-item>

          <el-form-item label="岗位" prop="postId">
            <el-select v-model="addForm.postId" placeholder="请选择岗位" style="width: 185px;">
              <el-option v-for="item in postList" :key="item.postId" :label="item.postName" :value="item.postId" />
            </el-select>
          </el-form-item>
          <el-form-item label="角色" prop="roleIdList">
            <el-select v-model="addForm.roleIdList" multiple placeholder="请选择角色" style="width: 185px;">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </el-select>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="addForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="addForm.remark" type="textarea" :rows="2" style="width: 455px" />
          </el-form-item>

        </el-form>
        <!--底部区域-->
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addClick">确 定</el-button>
      </span>
    </el-dialog>

    <!--编辑用户对话框-->
    <el-dialog title="编辑用户" :close-on-click-modal="false" :visible.sync="editDialogVisible" width="600px" @close="editHandleClose">
      <span>
        <el-form ref="editFormRef" :inline="true" :model="editForm" label-width="70px">
          <el-form-item label="账号" prop="userName">
            <el-input v-model="editForm.userName" disabled />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="editForm.nickName" />
          </el-form-item>
          <el-form-item label="部门" prop="deptId">
            <treeselect v-model="editForm.deptId" :options="deptTree" :normalizer="normalizer" style="width: 185px;" placeholder="请选择部门" />
          </el-form-item>
          <el-form-item label="岗位" prop="postId">
            <el-select v-model="editForm.postId" placeholder="请选择岗位" style="width: 185px;">
              <el-option v-for="item in postList" :key="item.postId" :label="item.postName" :value="item.postId" />
            </el-select>
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="editForm.roleIdList" multiple placeholder="请选择角色" style="width: 185px">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="editForm.remark" type="textarea" :rows="2" style="width: 455px" />
          </el-form-item>
        </el-form>
        <!--底部区域-->
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="editClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import { add, edit, del, listUser, getUser, exportUser, editStatus } from '@/api/system/user'
import { listRole } from '@/api/system/role'
import { treeDept } from '@/api/system/dept'
import { listSysPostAll } from '@/api/system/post'

import { downloadFile } from '@/utils/index'

export default {
  name: 'User',
  components: { Treeselect },
  data() {
    return {
      addDialogVisible: false,
      editDialogVisible: false,
      allotDialogVisible: false,
      showSearch: true,
      pageNumber: 1,
      pageSize: 10,
      total: 1,
      currentDept: undefined,
      deptTree: [],
      deptTreeProps: {
        checkStrictly: true,
        children: 'children',
        label: 'deptName',
        value: 'deptId'
      },
      postList: [],
      deptName: '',
      roleList: [],
      ids: [],
      listForm: [],
      editForm: {},
      addForm: {
        userName: '',
        passWord: '',
        deptId: undefined,
        email: '',
        sex: 1,
        nickName: '',
        remark: '',
        roleIdList: []
      },
      createDate: [],
      queryForm: {
        userName: '',
        startDate: '',
        endDate: ''
      },
      tableColumns: [{
        label: 'ID',
        value: 'userId',
        visible: true
      },
      {
        label: '用户名',
        value: 'userName',
        visible: true
      },
      {
        label: '昵称',
        value: 'nickName',
        visible: true
      },
      {
        label: '部门',
        value: 'deptName',
        visible: true
      },
      {
        label: '性别',
        value: 'sex',
        visible: true
      },
      {
        label: '状态',
        value: 'status',
        visible: true
      },
      {
        label: '备注',
        value: 'remark',
        visible: true
      },
      {
        label: '创建日期',
        value: 'createTime',
        visible: true
      }],
      addFormRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        passWord: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
        roleIdList: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.treeBox.filter(val)
    }
  },
  created() {
    // 初始化用户列表
    this.initListUser(this.user.deptId)
    this.initListRole()
    this.initListDept()
    this.initListPost()
  },

  methods: {
    // 查询按钮
    searchQuery() {
      if (this.createDate.length > 0) {
        this.queryForm.startDate = this.createDate[0]
        this.queryForm.endDate = this.createDate[1]
      }
      this.searchListUser()
    },
    // 重置按钮
    resetQuery() {
      this.createDate = []
      this.queryForm = {}
      this.initListUser(this.user.deptId)
    },
    // 刷新按钮
    refresh() {
      // 根据用户的部门id来查用户列表
      this.searchListUser()
    },

    // 添加按钮
    addBtn() {
      this.addDialogVisible = true
    },
    // 确认添加用户
    addClick() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        add(this.addForm).then(res => {
          this.$message.success(res.message)
          // 刷新数据
          this.initListUser(this.currentDept)
          // 关闭对话框
          this.addDialogVisible = false
        })
      })
    },

    // 编辑按钮
    editBtn(id) {
      this.editDialogVisible = true
      getUser(id).then(res => {
        if (res.code === 20000) {
          this.editForm = res.data
        }
      })
    },
    // 确认编辑用户
    editClick() {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return
        edit(this.editForm).then(res => {
          if (res.code === 20000) {
            this.$message.success(res.message)
            // 刷新数据
            this.initListUser(this.currentDept)
          }
          // 关闭对话框
          this.editDialogVisible = false
        })
      })
    },

    // 批量删除按钮
    delAllBtn(ids) {
      const data = {
        ids: ids
      }
      this.delUser(data, this.currentDept)
    },
    // 删除按钮
    delBtn(row) {
      this.ids = []
      this.ids.push(row.userId)
      const data = {
        ids: this.ids
      }
      this.delUser(data, row.deptId)
      this.ids = []
    },

    delUser(userId, deptId) {
      this.$confirm('此操作将永久删除【' + this.ids.length + '条数据】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认操作
        del(userId, deptId).then(res => {
          if (res.code === 20000) {
            this.$message.success(res.message)
            // 刷新数据
            this.initListUser(deptId)
          }
        })
      })
    },

    // 导出按钮
    exportClick() {
      const tableName = 'user'
      this.$confirm('是否确认导出所有用户数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认操作
        exportUser().then(data => {
          downloadFile(data, tableName, 'xlsx')
        })
      })
    },

    // 筛选组织架构
    filterNode(value, data) {
      if (!value) return true
      return data.deptName.indexOf(value) !== -1
    },
    // 切换部门
    handleNodeClick(data) {
      this.currentDept = data.deptId
      this.$nextTick(() => {
        // treeBox 元素的ref   value 绑定的node-key
        this.$refs.treeBox.setCurrentKey(this.deptTree[0].departmentId)
      })
      this.initListUser(this.currentDept)
    },

    /** 转换部门数据结构 */
    normalizer(node) {
      // 删除没有子节点的children属性
      if (node.children == null || node.children === 'null') {
        delete node.children
      }
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },

    // 由于element 上传组件有跨域问题，使用自定义创建表单发送请求
    // myUpload(content) {
    //   const formData = new FormData()
    //   formData.append('file', content.file) // 'file[]' 代表数组 其中`file`是可变的
    //   importUser(formData).then(res => {
    //     //
    //     this.$message.success(res.message)
    //   }).catch(err => {
    //     // 失败
    //     console.log(err)
    //   })
    // },

    // 表格全选
    handleSelectionChange(val) {
      this.ids = []
      for (let index = 0; index < val.length; index++) {
        this.ids.push(val[index].userId)
      }
    },

    // 修改状态
    userStateChanged(user) {
      editStatus(user).then(res => {
        if (res.code === 20000) {
          this.$message.success(res.message)
          // 刷新数据
          this.initListUser(user.deptId)
        }
      })
    },

    // 监听当前页的事件
    handleCurrentChange(pageIndex) {
      this.pageNumber = pageIndex
      this.searchListUser()
    },

    // 监听当前页的条数事件
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.searchListUser()
    },

    // 监听添加用户对话框的关闭事件，重置表单内容
    addHandleClose() {
      this.$refs.addFormRef.resetFields()
      this.addForm.roleIdList = []
    },

    // 监听编辑用户对话框的关闭事件,重置表单内容
    editHandleClose() {
      this.$refs.editFormRef.resetFields()
      this.addForm.roleIdList = []
    },

    // 条件查询
    searchListUser() {
      // 根据用户的部门id来查用户列表
      const page = {
        pageNum: this.pageNumber,
        pageSize: this.pageSize,
        currentDept: this.currentDept
      }
      listUser(this.queryForm, page).then(res => {
        this.listForm = res.data.records
        this.total = res.data.total
        this.pageNum = res.data.current
      })
    },
    // 初始化用户数据
    initListUser(deptId) {
      // 根据用户的部门id来查用户列表
      const page = {
        pageNum: this.pageNumber,
        pageSize: this.pageSize,
        currentDept: deptId
      }
      listUser(null, page).then(res => {
        this.listForm = res.data.records
        this.total = res.data.total
        this.pageNum = res.data.current
        this.currentDept = deptId
      })
    },
    // 初始化角色数据
    initListRole() {
      const page = {
        pageNum: this.pageNumber,
        pageSize: this.pageSize
      }
      listRole(null, page).then(res => {
        this.roleList = res.data.records
        this.total = res.data.total
        this.pageNum = res.data.current
      })
    },
    // 初始化部门
    initListDept() {
      treeDept().then(res => {
        this.deptTree = res.data
      })
    },
    // 初始化岗位
    initListPost() {
      listSysPostAll().then(res => {
        this.postList = res.data
      })
    }
  }
}
</script>

<style scoped>
</style>
